import Vue from 'vue'

import Cookies from 'js-cookie'

import 'normalize.css/normalize.css' // A modern alternative to CSS resets

import Element from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'

import '@/styles/index.scss' // global css

import App from './App'
import router from './router'
import store from './store'

import './icons' // icon
import './permission' // permission control

import * as filters from './filters' // global filters

import permission from '@/directive/permission/index.js' // 权限判断指令

Vue.use(Element, {
  size: Cookies.get('size') || 'small' // set element-ui default size
})

Vue.directive('permission', permission)

// register global utility filters.
Object.keys(filters).forEach(key => {
  Vue.filter(key, filters[key])
})

Vue.config.productionTip = false

new Vue({
  el: '#app',
  router,
  store,
  render: h => h(App)
})

let cache = null
let keys = []
Vue.mixin({
  beforeRouteLeave(to, from, next) {
    const isExit = this.$store.state.tagsView.visitedViews.filter(tab => tab.path === from.fullPath)[0]
    if (!isExit && this.$vnode.parent && this.$vnode.parent.componentInstance.cache) {
      const key = from.fullPath // 当前关闭的组件名
      cache = this.$vnode.parent.componentInstance.cache // 缓存的组件
      keys = this.$vnode.parent.componentInstance.keys // 缓存的组件名
      keys.forEach((e, i) => {
        if (e.substr(e.indexOf('/')) === key) {
          cache[e].componentInstance.$destroy()
          cache[e] = null
          keys.splice(i, 1)
        }
      })
    }
    next()
  }
})
